<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>企业公告智能监控大屏 - 系统运行状态</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        body {
            background: linear-gradient(135deg, #1E293B 0%, #0F172A 100%);
            min-height: 100vh;
        }
        .chart-container {
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        .kpi-card {
            background: linear-gradient(135deg, #334155 0%, #1E293B 100%);
            box-shadow: 0 8px 32px 0 rgba(51, 65, 85, 0.3);
        }
        .status-healthy {
            background: linear-gradient(135deg, #059669 0%, #047857 100%);
            animation: pulse-healthy 3s infinite;
        }
        .status-warning {
            background: linear-gradient(135deg, #D97706 0%, #92400E 100%);
            animation: pulse-warning 2s infinite;
        }
        .status-critical {
            background: linear-gradient(135deg, #DC2626 0%, #991B1B 100%);
            animation: pulse-critical 1s infinite;
        }
        @keyframes pulse-healthy {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.8; }
        }
        @keyframes pulse-warning {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
        @keyframes pulse-critical {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.6; }
        }
        .metric-card {
            transition: all 0.3s ease;
        }
        .metric-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 40px 0 rgba(51, 65, 85, 0.4);
        }
    </style>
</head>
<body class="text-white">
    <!-- 顶部导航 -->
    <header class="bg-black bg-opacity-20 backdrop-blur-md border-b border-white border-opacity-20 p-4">
        <div class="container mx-auto flex justify-between items-center">
            <h1 class="text-2xl font-bold">系统运行状态大屏</h1>
            <div class="flex space-x-6">
                <a href="/" class="text-white hover:text-blue-300">总览</a>
                <a href="/source" class="text-white hover:text-blue-300">来源分析</a>
                <a href="/sentiment" class="text-white hover:text-blue-300">情感分析</a>
                <a href="/risk" class="text-white hover:text-blue-300">风险监控</a>
                <a href="/system" class="text-blue-300 font-semibold">系统状态</a>
            </div>
            <div class="text-sm">
                <span id="update-time">更新时间: --</span>
            </div>
        </div>
    </header>

    <main class="container mx-auto p-6">
        <!-- 系统健康状态总览 -->
        <div class="grid grid-cols-1 md:grid-cols-5 gap-6 mb-8">
            <div class="kpi-card rounded-xl p-6 text-center metric-card" id="system-status-card">
                <div class="text-2xl font-bold mb-2" id="system-status">系统正常</div>
                <div class="text-sm opacity-80">系统状态</div>
            </div>
            <div class="kpi-card rounded-xl p-6 text-center metric-card">
                <div class="text-3xl font-bold mb-2 text-blue-300" id="total-processed">-</div>
                <div class="text-sm opacity-80">总处理量</div>
            </div>
            <div class="kpi-card rounded-xl p-6 text-center metric-card">
                <div class="text-3xl font-bold mb-2 text-green-300" id="success-rate">-</div>
                <div class="text-sm opacity-80">成功率</div>
            </div>
            <div class="kpi-card rounded-xl p-6 text-center metric-card">
                <div class="text-3xl font-bold mb-2 text-yellow-300" id="processing-coverage">-</div>
                <div class="text-sm opacity-80">处理覆盖率</div>
            </div>
            <div class="kpi-card rounded-xl p-6 text-center metric-card">
                <div class="text-3xl font-bold mb-2 text-purple-300" id="avg-pdf-size">-</div>
                <div class="text-sm opacity-80">平均PDF大小</div>
            </div>
        </div>

        <!-- 处理性能指标 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="chart-container rounded-xl p-4 text-center metric-card">
                <div class="text-xl font-bold mb-1 text-cyan-300" id="avg-pdf-pages">-</div>
                <div class="text-xs opacity-80">平均PDF页数</div>
            </div>
            <div class="chart-container rounded-xl p-4 text-center metric-card">
                <div class="text-xl font-bold mb-1 text-orange-300" id="processing-failed">-</div>
                <div class="text-xs opacity-80">处理失败</div>
            </div>
            <div class="chart-container rounded-xl p-4 text-center metric-card">
                <div class="text-xl font-bold mb-1 text-pink-300" id="not-processed">-</div>
                <div class="text-xs opacity-80">未处理</div>
            </div>
            <div class="chart-container rounded-xl p-4 text-center metric-card">
                <div class="text-xl font-bold mb-1 text-indigo-300" id="database-size">-</div>
                <div class="text-xs opacity-80">数据库大小</div>
            </div>
        </div>

        <!-- 处理趋势和性能分析 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- 近期处理量趋势 -->
            <div class="chart-container rounded-xl p-6">
                <h3 class="text-lg font-semibold mb-4">近7天处理量趋势</h3>
                <div id="processing-trend-chart" style="height: 300px;"></div>
            </div>

            <!-- 系统性能仪表盘 -->
            <div class="chart-container rounded-xl p-6">
                <h3 class="text-lg font-semibold mb-4">系统性能仪表盘</h3>
                <div id="performance-gauge-chart" style="height: 300px;"></div>
            </div>
        </div>

        <!-- 数据质量和存储状态 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- 数据质量检查 -->
            <div class="chart-container rounded-xl p-6">
                <h3 class="text-lg font-semibold mb-4">数据质量检查</h3>
                <div class="space-y-4" id="data-quality-metrics">
                    <!-- 数据质量指标 -->
                </div>
            </div>

            <!-- 存储容量统计 -->
            <div class="chart-container rounded-xl p-6">
                <h3 class="text-lg font-semibold mb-4">存储容量统计</h3>
                <div id="storage-chart" style="height: 200px;"></div>
                <div class="grid grid-cols-2 gap-4 mt-4">
                    <div class="text-center bg-blue-900 bg-opacity-30 rounded p-3">
                        <div class="text-lg font-bold text-blue-300" id="announcements-count">-</div>
                        <div class="text-xs text-blue-200">公告记录</div>
                    </div>
                    <div class="text-center bg-green-900 bg-opacity-30 rounded p-3">
                        <div class="text-lg font-bold text-green-300" id="insights-count">-</div>
                        <div class="text-xs text-green-200">分析记录</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 实时监控和告警 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 系统告警日志 -->
            <div class="chart-container rounded-xl p-6">
                <h3 class="text-lg font-semibold mb-4 text-yellow-300">系统告警监控</h3>
                <div id="system-alerts" class="space-y-3 max-h-60 overflow-y-auto">
                    <!-- 告警列表 -->
                </div>
            </div>

            <!-- 处理队列状态 -->
            <div class="chart-container rounded-xl p-6">
                <h3 class="text-lg font-semibold mb-4">处理队列状态</h3>
                <div class="grid grid-cols-3 gap-4">
                    <div class="text-center bg-blue-900 bg-opacity-30 rounded-lg p-4">
                        <div class="text-2xl font-bold text-blue-300" id="queue-pending">-</div>
                        <div class="text-sm text-blue-200">等待处理</div>
                    </div>
                    <div class="text-center bg-yellow-900 bg-opacity-30 rounded-lg p-4">
                        <div class="text-2xl font-bold text-yellow-300" id="queue-processing">-</div>
                        <div class="text-sm text-yellow-200">正在处理</div>
                    </div>
                    <div class="text-center bg-green-900 bg-opacity-30 rounded-lg p-4">
                        <div class="text-2xl font-bold text-green-300" id="queue-completed">-</div>
                        <div class="text-sm text-green-200">处理完成</div>
                    </div>
                </div>
                <div class="mt-4">
                    <div class="bg-gray-900 bg-opacity-30 rounded-lg p-4">
                        <h4 class="text-sm font-medium mb-2">处理统计</h4>
                        <div class="text-xs text-gray-300" id="processing-stats">
                            平均处理时间: --<br>
                            当前处理速度: --<br>
                            预计完成时间: --
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <script>
        let charts = {};
        let systemData = {};
        
        document.addEventListener('DOMContentLoaded', function() {
            loadData();
            setInterval(loadData, 30000); // 每30秒刷新
        });

        async function loadData() {
            try {
                await Promise.all([
                    loadProcessingStats(),
                    loadDailyProcessing(),
                    loadDataQuality(),
                    loadStorageStats()
                ]);
                updateSystemStatus();
                document.getElementById('update-time').textContent = `更新时间: ${new Date().toLocaleString()}`;
            } catch (error) {
                console.error('加载系统状态数据失败:', error);
            }
        }

        async function loadProcessingStats() {
            const response = await fetch('/api/system/processing-stats');
            const data = await response.json();
            systemData.processing = data;
            
            // 更新KPI指标
            document.getElementById('total-processed').textContent = data.total_announcements.toLocaleString();
            document.getElementById('success-rate').textContent = `${data.success_rate}%`;
            document.getElementById('processing-coverage').textContent = `${data.processing_coverage}%`;
            document.getElementById('avg-pdf-size').textContent = `${data.avg_pdf_size_kb}KB`;
            document.getElementById('avg-pdf-pages').textContent = `${data.avg_pdf_pages}页`;
            document.getElementById('processing-failed').textContent = data.processing_failed.toLocaleString();
            document.getElementById('not-processed').textContent = data.not_processed.toLocaleString();
            
            // 更新性能仪表盘
            updatePerformanceGaugeChart(data);
        }

        async function loadDailyProcessing() {
            const response = await fetch('/api/system/daily-processing?days=7');
            const data = await response.json();
            
            updateProcessingTrendChart(data);
        }

        async function loadDataQuality() {
            const response = await fetch('/api/system/data-quality');
            const data = await response.json();
            
            updateDataQualityMetrics(data);
        }

        async function loadStorageStats() {
            const response = await fetch('/api/system/storage-stats');
            const data = await response.json();
            
            document.getElementById('database-size').textContent = `${data.database_size_mb}MB`;
            document.getElementById('announcements-count').textContent = data.announcements_count.toLocaleString();
            document.getElementById('insights-count').textContent = data.insights_count.toLocaleString();
            
            updateStorageChart(data);
        }

        function updateSystemStatus() {
            const processing = systemData.processing;
            if (!processing) return;
            
            const statusCard = document.getElementById('system-status-card');
            const statusText = document.getElementById('system-status');
            
            let status = '系统正常';
            let statusClass = 'status-healthy';
            
            if (processing.success_rate < 50) {
                status = '系统异常';
                statusClass = 'status-critical';
            } else if (processing.success_rate < 80) {
                status = '系统警告';
                statusClass = 'status-warning';
            }
            
            statusText.textContent = status;
            statusCard.className = `kpi-card rounded-xl p-6 text-center metric-card ${statusClass}`;
            
            // 更新队列状态（模拟数据）
            updateQueueStatus(processing);
            
            // 更新告警信息
            updateSystemAlerts(processing);
        }

        function updateProcessingTrendChart(data) {
            const chartDom = document.getElementById('processing-trend-chart');
            if (!charts.processingTrend) {
                charts.processingTrend = echarts.init(chartDom);
            }
            
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'cross' }
                },
                legend: {
                    data: ['总量', '成功处理', '处理失败'],
                    textStyle: { color: '#fff' }
                },
                xAxis: {
                    type: 'category',
                    data: data.map(item => item.date),
                    axisLabel: { color: '#fff' }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: { color: '#fff' }
                },
                series: [
                    {
                        name: '总量',
                        type: 'line',
                        data: data.map(item => item.daily_total),
                        smooth: true,
                        itemStyle: { color: '#60A5FA' }
                    },
                    {
                        name: '成功处理',
                        type: 'line',
                        data: data.map(item => item.daily_processed),
                        smooth: true,
                        itemStyle: { color: '#10B981' }
                    },
                    {
                        name: '处理失败',
                        type: 'line',
                        data: data.map(item => item.daily_failed),
                        smooth: true,
                        itemStyle: { color: '#EF4444' }
                    }
                ]
            };
            
            charts.processingTrend.setOption(option);
        }

        function updatePerformanceGaugeChart(data) {
            const chartDom = document.getElementById('performance-gauge-chart');
            if (!charts.performanceGauge) {
                charts.performanceGauge = echarts.init(chartDom);
            }
            
            const option = {
                series: [
                    {
                        name: '成功率',
                        type: 'gauge',
                        center: ['25%', '50%'],
                        radius: '60%',
                        min: 0,
                        max: 100,
                        splitNumber: 10,
                        axisLine: {
                            lineStyle: {
                                width: 6,
                                color: [
                                    [0.3, '#EF4444'],
                                    [0.7, '#F59E0B'],
                                    [1, '#10B981']
                                ]
                            }
                        },
                        pointer: { itemStyle: { color: 'auto' } },
                        axisTick: { length: 12 },
                        splitLine: { length: 20 },
                        axisLabel: { color: 'white', fontSize: 12 },
                        title: {
                            offsetCenter: [0, '-30%'],
                            fontSize: 14,
                            color: 'white'
                        },
                        detail: {
                            fontSize: 20,
                            offsetCenter: [0, '-10%'],
                            valueAnimation: true,
                            formatter: function (value) {
                                return Math.round(value) + '%';
                            },
                            color: 'auto'
                        },
                        data: [{ value: data.success_rate, name: '成功率' }]
                    },
                    {
                        name: '覆盖率',
                        type: 'gauge',
                        center: ['75%', '50%'],
                        radius: '60%',
                        min: 0,
                        max: 100,
                        splitNumber: 10,
                        axisLine: {
                            lineStyle: {
                                width: 6,
                                color: [
                                    [0.3, '#EF4444'],
                                    [0.7, '#F59E0B'],
                                    [1, '#10B981']
                                ]
                            }
                        },
                        pointer: { itemStyle: { color: 'auto' } },
                        axisTick: { length: 12 },
                        splitLine: { length: 20 },
                        axisLabel: { color: 'white', fontSize: 12 },
                        title: {
                            offsetCenter: [0, '-30%'],
                            fontSize: 14,
                            color: 'white'
                        },
                        detail: {
                            fontSize: 20,
                            offsetCenter: [0, '-10%'],
                            valueAnimation: true,
                            formatter: function (value) {
                                return Math.round(value) + '%';
                            },
                            color: 'auto'
                        },
                        data: [{ value: data.processing_coverage, name: '覆盖率' }]
                    }
                ]
            };
            
            charts.performanceGauge.setOption(option);
        }

        function updateDataQualityMetrics(data) {
            const container = document.getElementById('data-quality-metrics');
            
            const metrics = [
                { name: '标题完整性', value: data.title_completeness, icon: '📝' },
                { name: '公司信息完整性', value: data.company_completeness, icon: '🏢' },
                { name: '时间完整性', value: data.time_completeness, icon: '⏰' },
                { name: 'PDF链接完整性', value: data.link_completeness, icon: '🔗' }
            ];
            
            container.innerHTML = metrics.map(metric => {
                const color = metric.value >= 95 ? 'green' : metric.value >= 90 ? 'yellow' : 'red';
                return `
                    <div class="bg-${color}-900 bg-opacity-30 rounded-lg p-4 flex justify-between items-center">
                        <div class="flex items-center space-x-3">
                            <span class="text-2xl">${metric.icon}</span>
                            <span class="text-sm font-medium">${metric.name}</span>
                        </div>
                        <div class="text-right">
                            <div class="text-lg font-bold text-${color}-300">${metric.value}%</div>
                            <div class="text-xs text-${color}-200">完整度</div>
                        </div>
                    </div>
                `;
            }).join('');
        }

        function updateStorageChart(data) {
            const chartDom = document.getElementById('storage-chart');
            if (!charts.storageChart) {
                charts.storageChart = echarts.init(chartDom);
            }
            
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c}条记录'
                },
                series: [{
                    name: '数据分布',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    center: ['50%', '50%'],
                    data: [
                        { 
                            value: data.announcements_count, 
                            name: '公告记录',
                            itemStyle: { color: '#60A5FA' }
                        },
                        { 
                            value: data.insights_count, 
                            name: '分析记录',
                            itemStyle: { color: '#10B981' }
                        }
                    ],
                    label: {
                        color: '#fff',
                        formatter: '{b}\n{c}条'
                    }
                }]
            };
            
            charts.storageChart.setOption(option);
        }

        function updateQueueStatus(data) {
            // 模拟队列数据
            const pending = data.not_processed || 0;
            const processing = Math.floor(Math.random() * 10); // 模拟正在处理的数量
            const completed = data.processed_successfully || 0;
            
            document.getElementById('queue-pending').textContent = pending.toLocaleString();
            document.getElementById('queue-processing').textContent = processing.toLocaleString();
            document.getElementById('queue-completed').textContent = completed.toLocaleString();
            
            // 更新处理统计
            const avgTime = '2.3秒';
            const currentSpeed = '45个/分钟';
            const estimatedTime = pending > 0 ? `${Math.ceil(pending / 45)}分钟` : '已完成';
            
            document.getElementById('processing-stats').innerHTML = `
                平均处理时间: ${avgTime}<br>
                当前处理速度: ${currentSpeed}<br>
                预计完成时间: ${estimatedTime}
            `;
        }

        function updateSystemAlerts(data) {
            const container = document.getElementById('system-alerts');
            const alerts = [];
            
            // 根据系统状态生成告警
            if (data.success_rate < 50) {
                alerts.push({
                    level: 'critical',
                    message: '系统处理成功率过低，需要立即检查',
                    time: new Date().toLocaleTimeString()
                });
            }
            
            if (data.processing_coverage < 60) {
                alerts.push({
                    level: 'warning',
                    message: '处理覆盖率较低，建议增加处理资源',
                    time: new Date().toLocaleTimeString()
                });
            }
            
            if (data.avg_pdf_size_kb > 5000) {
                alerts.push({
                    level: 'info',
                    message: 'PDF文件平均大小较大，可能影响处理速度',
                    time: new Date().toLocaleTimeString()
                });
            }
            
            if (alerts.length === 0) {
                alerts.push({
                    level: 'success',
                    message: '系统运行正常，所有指标正常',
                    time: new Date().toLocaleTimeString()
                });
            }
            
            container.innerHTML = alerts.map(alert => {
                const colors = {
                    critical: 'bg-red-900 border-red-500 text-red-200',
                    warning: 'bg-yellow-900 border-yellow-500 text-yellow-200',
                    info: 'bg-blue-900 border-blue-500 text-blue-200',
                    success: 'bg-green-900 border-green-500 text-green-200'
                };
                
                const icons = {
                    critical: '🚨',
                    warning: '⚠️',
                    info: 'ℹ️',
                    success: '✅'
                };
                
                return `
                    <div class="${colors[alert.level]} border border-opacity-50 rounded-lg p-3">
                        <div class="flex items-start space-x-3">
                            <span class="text-lg">${icons[alert.level]}</span>
                            <div class="flex-1">
                                <div class="text-sm font-medium">${alert.message}</div>
                                <div class="text-xs opacity-80">${alert.time}</div>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 响应式处理
        window.addEventListener('resize', function() {
            Object.values(charts).forEach(chart => {
                if (chart) chart.resize();
            });
        });
    </script>
</body>
</html> 